//
//  TaskViewController.m
//  WorkingResult
//
//  Created by 河野 智遵 on 11/08/15.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "TaskEditRootViewController.h"
#import "Task.h"

@implementation TaskEditRootViewController

#pragma mark - View lifecycle

@synthesize model;

- (void)viewDidLoad
{
    [super viewDidLoad];

    taskList_ = [[TaskListViewController alloc] initWithStyle:UITableViewStyleGrouped];
    taskList_.moveToAddingTaskEditorActionTarget = self;
    taskList_.moveToAddingTaskEditorAction = @selector(on_taskList_moveToAddingTaskEditor);
    
    taskList_.model = self.model;
    taskList_.moveToUpdatingTaskEditorActionTarget = self;
    taskList_.moveToUpdatingTaskEditorAction = @selector(on_taskList_moveToUpdatingTaskEditor);

    taskEdit_ = [[TaskEditViewController alloc] init];
    taskEdit_.doneActionTarget = self;
    taskEdit_.doneAction = @selector(on_taskEdit_done);
    
    taskNavigation_ = [[UINavigationController alloc] initWithRootViewController:taskList_];
    
    [self.view addSubview:taskNavigation_.view];
}

- (void)on_taskList_moveToUpdatingTaskEditor
{
    [taskEdit_ clear];
    taskEdit_.mode = UPDATE;
    taskEdit_.task = [model taskAtIndex:[taskList_ getSelectedTaskIndex_]];
    [taskNavigation_ pushViewController:taskEdit_ animated:YES];
}

- (void)on_taskEdit_done
{
    switch (taskEdit_.mode)
    {
        case ADD:
            [self.model addTask:taskEdit_.task];
            break;
        case UPDATE:
            [self.model updateTask:taskEdit_.task index:taskList_.selectedTaskIndex_];
            break;
        default:
            break;
    }
    [taskList_.tableView reloadData];
    [taskList_ viewWillAppear:YES]; // ←これは書かなくても動作するね・・・
}

-(void)on_taskList_moveToAddingTaskEditor
{
    [taskEdit_ clear];
    taskEdit_.mode = ADD;
    [taskNavigation_ pushViewController:taskEdit_ animated:YES];
}

- (void)viewDidUnload
{
    [taskList_ release];
    [taskNavigation_ release];
    [taskEdit_ release];
    [self.model release];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
